<?php namespace App\Models\Power;

use App\Models\Base\PowerBase;
use App\Models\Power\Pile;

class Gun extends PowerBase {

    protected $table = 'cdz_electric_gun';

    protected $fillable = [];

    protected $dates = [];

    public static $rules = [
        // Validation rules
    ];

    /**
     * 根据枪口号查询电桩是否被占用
     * params1 String $no
     * params2 Int $pile_id
     */
    public function getPileUsing($pile_no, $pile_id) {

        $result = ['count_gun'=>0, 'count_not_using'=>0, 'is_using'=>0];
        $redis_info = $this -> redis -> hgetall('CDZCHARGEORDERPILENO');
        $query = self::query();
        $query -> where('pile_id', $pile_id);
        $guns = $query -> get() -> toArray();
        $count_gun = count($guns);

        $count_use = 0;
        foreach($redis_info as $key => $value) {
            if(explode('_', $key)[0] == $pile_no) {
                $count_use+=1;
            }
        }

        $result['count_gun'] = $count_gun;
        $result['count_not_using'] = $count_gun - $count_use;

        if($count_use >= $count_gun) {
            $result['is_using'] = 1;
        } else {
            $result['is_using'] = 0;
        }

        return $result;
        
    }

    /**
     * 和Pile模型的多对一关联
     */
    public function pile() {
        return $this->belongsTo('App\Models\Pile', 'pile_id');
    }



}
